include Gosu
include Globals

class Enemy < GameObject

  def initialize(screen, game)
    super(screen)
    @screen = screen
    @game = game
    @images = {}
    @soundfx = {}
    
    # change made 6/16/10 for enhanced graphics
    # icon = game.images["ship_enemy.png"]
    #icons = Image.load_tiles(game, "3d_renders/ship_enemy.png", 65, 65, true)
    icons = game.load_tiles("ship_enemy.png", 65, 65, true)

    bullet = game.load_tiles("bullet_red.png", 10, 40)
    explode_particle = game.images["../3d_renders/particle.png"]
    e_img = game.images["explosion.png"]
    @images["icon"] = icons
    @images["bullet"] = bullet
    @images["particle"] = explode_particle
    @images["explosion"] = e_img

    shoot_sound = game.sounds["shoot_enemy_remix.ogg"]
    explode_sound = game.sounds["die_enemy_remix.ogg"]
    appear_sound = game.sounds["appear_enemy_remix.ogg"]
    @soundfx["appear"] = appear_sound
    @soundfx["shoot"] = shoot_sound
    @soundfx["explode"] = explode_sound

    @x, @y = 0, HEIGHT/2
    @angle = 0
    @charge = 60
    @shoot_type = :enemy_bullet
    @screen.add_enemy(self)
    @destroyed = false
    if @screen.game_options["sound"]
      @soundfx["appear"].play.volume = @screen.game_options["sound_volume"]
    end
  end

  def update
    @x += 2
    player = @screen.players[rand(@screen.players.length)] unless @screen.players.empty?
    shoot(player) unless !@screen.players.empty? and !player.obj_id
    @charge += 1
    return false if @x == WIDTH + 40 or @destroyed
    true
  end

  def draw
    # change made 6/16/10 for enhanced graphics
    # @images["icon"].draw_rot(@x, @y, ASTEROID_Z, @angle, 0.5, 0.5)
    @images["icon"][(@x/5 % 27).floor.to_i].draw_rot(@x, @y, ASTEROID_Z, @angle, 0.5, 0.5)
    # (@x/div % frames) = index(0..15)
    # currently means while @x increments by 2 in update(), advance a
    # stage in the sprite every 2.5 frames (27 frames in the sprite total). 
    # Complete a cycle in approx 67 frames or approx. 1.1 seconds. 
    # "div" and the cycle time are directly proportional.
  end

  def obj_id
    return :enemy
  end

  def shoot(target)
    return if @charge < 100 or !target
    shoot_at = angle(@x, @y, target.x, target.y)
    Bullet.new(@screen, @game, @images["bullet"], @x, @y, shoot_at, @shoot_type)
    if @screen.game_options["sound"]
      @soundfx["shoot"].play.volume = @screen.game_options["sound_volume"]
    end
    @charge = 0
  end
  
  def check(x, y, distance)
    die if distance(x, y, @x, @y) < distance
  end

  def die
    Explosion.new(@screen, @game, @images["particle"], @images["explosion"],
                  @x, @y, ASTEROID_Z)
    if @screen.game_options["sound"]
      @soundfx["explode"].play.volume = @screen.game_options["sound_volume"]
    end
    @destroyed = true
    @screen.remove_enemy(self)
  end

end
